﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ccit.ClassLibrary;
using Ccit.Utils;
using Newtonsoft.Json;

namespace Ccit.SysPlat.Organ
{
    /// <summary>
    /// Description: 系统平台组织机构 -> 部门管理维护页面
    /// Author: tim 2010-01-29
    /// </summary>
    public partial class sys_dept_edit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                _hidOrganId.Value = (null != Request.QueryString["organId"]) ? Request.QueryString["organId"].ToString() : "1";
                _hidDeptId.Value = (null != Request.QueryString["deptId"]) ? Request.QueryString["deptId"].ToString() : string.Empty;
                ViewState["updeptId"] = (null != Request.QueryString["updeptId"]) ? Request.QueryString["updeptId"].ToString() : string.Empty;                
                initializePage();
            }
        }

        private void initializePage()
        {
            #region 获取部门名称校验系统开关
            /* 业务逻辑:
             *     在当做集团版处理时,部门名称是应该可以重复的 
             * Commer: tim 2010-03-17 */

            _hidDeptNameChk.Value = ConfigLib.GetAttribute("CCIT_SYSTEM/CCIT_DEPTNAME", eValueType.TEXT);
            _hidDeptNameChk.Value = (string.IsNullOrEmpty(_hidDeptNameChk.Value)) ? "0" : _hidDeptNameChk.Value;  //默认需要校验
            #endregion

            DeptBLL deptBLL = new DeptBLL();
            string deptId = _hidDeptId.Value; 

            initializeAddNew(deptBLL);

            MsDept msDept = deptBLL.GetDeptInfo(deptId, eTrueFalse.TRUE);
            if (null != msDept) initializeEdit(msDept);                
            else {
                if (ViewState["updeptId"].ToString() != "")
                {
                    initializeAddSub();
                }
            }

            msDept = null;
            deptBLL.Release();
            deptBLL = null;

        }

        private void initializeAddNew(DeptBLL deptBLL)
        {
            string organId = _hidOrganId.Value;
            OrganBLL organBLL = new OrganBLL();
            MsOrgan msOrgan = organBLL.GetOrganInfo(organId);
            lbOrganName.Text = getOrganName(msOrgan);
            
            #region 缺初始化上级部门选择下拉控件
            string deptId = _hidDeptId.Value;
            string upDeptId = _hidUpDeptId.Value;
            
            List<MsKeyValue> lstDept = deptBLL.GetALLDepts(organId, deptId);            
            CtrInterface.BindDropDown(ref ddlUpDept, lstDept,true,string.Empty, true, upDeptId);
            #endregion

            txtDeptName.Text = string.Empty;
            txtDeptOrder.Text = string.Empty;
            txtDeptDesc.Text = string.Empty;
            _hidUserId.Value = string.Empty;
            txtUserName.Text = string.Empty;
            lstUserName.Items.Clear();
            _hidManagerId.Value = string.Empty;
            txtManager.Text = string.Empty;

            lstDept = null;
            msOrgan = null;
            organBLL.Release();
            organBLL = null;
            
        }

        private string getOrganName(MsOrgan msOrgan)
        {
            string organName = string.Empty;
            if (null != msOrgan)
                organName = msOrgan.organName;
            else
            {
                MsLoginUser loginUser = Session["LogUserInfo"] as MsLoginUser;
                organName = loginUser.organName;
                loginUser = null;
            }

            return organName;
        }

        private void initializeEdit(MsDept msDept)
        {
            txtDeptName.Text = msDept.deptName;

            string upDeptId = msDept.upDeptId;
            ddlUpDept.SelectedValue = upDeptId;
            _hidOriginUpDeptId.Value = upDeptId;
            _hidUpDeptId.Value = upDeptId;

            txtDeptOrder.Text = msDept.orderNo;
            txtDeptDesc.Text = msDept.deptDesc;

            string deptUserIds = msDept.includeUsers.key;
            string deptUserNames = msDept.includeUsers.val;
            _hidUserId.Value = deptUserIds;
            txtUserName.Text = deptUserNames;

            List<MsKeyValue> lstUser = convertUserInfo(deptUserIds, deptUserNames);
            CtrInterface.BindListBox(ref lstUserName, lstUser, false, string.Empty);

            _hidManagerId.Value = msDept.adminUserId;
            txtManager.Text = msDept.adminUserName;

            lstUser = null;
        }

        private List<MsKeyValue> convertUserInfo(string deptUserIds,string deptUserNames)
        {
            if(string.IsNullOrEmpty(deptUserIds)) return new List<MsKeyValue>();

            string[] userIdArray = deptUserIds.Split(',');
            string[] userNameArray = deptUserNames.Trim().Split(' ');
            int itemCount = userIdArray.Length;

            List<MsKeyValue> lstUser = new List<MsKeyValue>();
            MsKeyValue msUser;
            for (int i = 0; i < itemCount; i++)
            {                
                msUser = new MsKeyValue {
                    key = userIdArray[i],
                    val = userNameArray[i]
                };
                lstUser.Add(msUser);
            }

            return lstUser;
        }

        private void initializeAddSub()
        {
            string upDeptId = ViewState["updeptId"].ToString();
            ddlUpDept.SelectedValue = upDeptId;
            _hidOriginUpDeptId.Value = upDeptId;
            _hidUpDeptId.Value = upDeptId;
        }

        protected void lnbCallBack_Click(object sender, EventArgs e)
        {
            initializePage();
        }

        #region Ajax Methods

        /// <summary>
        /// 部门同名校验
        /// </summary>
        /// <param name="deptId">部门ID</param>
        /// <param name="deptName">部门名称</param>
        /// <param name="organId">机构ID</param>
        /// <returns></returns>
        [global::System.Web.Services.WebMethod]
        public static string CheckDeptNameExist(string deptId, string deptName, string organId)
        {
            DeptBLL deptBLL = new DeptBLL();
            bool bExist = deptBLL.IsExistSameName(deptId, deptName, organId);
            string resultSign = (bExist) ? "1" : "0";
            var newObj = new { operType = "DEPTNAMECHECK", resultSign = resultSign };
            string serExpr = JavaScriptConvert.SerializeObject(newObj);
            
            newObj = null;
            deptBLL.Release();
            deptBLL = null;
            return serExpr;
        }

        /// <summary>
        /// 部门保存
        /// </summary>
        /// <param name="jsonExpr">部门信息表达式</param>
        /// <param name="ctrlType">控制类型</param>
        /// <returns></returns>
        [global::System.Web.Services.WebMethod]
        public static string SaveDept(string jsonExpr,string ctrlType)
        {
            MsDept msDept = JavaScriptConvert.DeserializeObject(jsonExpr, typeof(MsDept)) as MsDept;
            DeptBLL deptBLL = new DeptBLL();
            List<string> lstResult = deptBLL.Save(msDept);
            var newObj = new
            {
                operType = "DEPTSAVE",
                ctrlType = ctrlType,
                deptId = lstResult[0],
                upDeptId = msDept.upDeptId,
                deptName = msDept.deptName.Trim(),
                isHasChild = lstResult[2],
                deptOrder = lstResult[3],
                resultMsg = lstResult[1]
            };
            string serExpr = JavaScriptConvert.SerializeObject(newObj);
            newObj = null;
            lstResult = null;
            msDept = null;
            deptBLL.Release();
            deptBLL = null;
            return serExpr;
        }

        /// <summary>
        /// 部门删除
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        [global::System.Web.Services.WebMethod]
        public static string DeleteDept(string deptId)
        {
            DeptBLL deptBLL = new DeptBLL();
            List<string> lstResult = deptBLL.Delete(deptId);
            var newObj = new
            {
                operType = "DEPTDELETE",                
                resultSign = lstResult[0],
                resultMsg = lstResult[1]
            };

            string serExpr = JavaScriptConvert.SerializeObject(newObj);
            newObj = null;
            lstResult = null;
            deptBLL.Release();
            deptBLL = null;
            return serExpr;
        }        
        #endregion
    }
}
